package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    //分页查询
    @GetMapping("/page")
    public R<Page> selectByPage(int page, int pageSize) {
        Page pg = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        Page page1 = categoryService.page(pg, lqw);
        return R.success(page1);
    }

    //添加
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    //删除
    @DeleteMapping
    public R<String> deleteByid(Long id) {
        boolean delete = categoryService.remove(id);
        return delete ? R.success("删除成功"):R.error("删除失败");
    }

    //修改
    @PutMapping
    public R<String> updateByid(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //菜品查询
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
